const { createApp } = Vue;

createApp({
    data() {
        return {
            // 摄像头相关
            showCamera: false,
            capturedImage: null,
            videoStream: null,
            canvas: null,
            // 状态控制
            isSubmitting: false,
            uploadProgress: 0,
            successMessage: '',
            errorMessage: '',
            errors: {},
            // 签到记录
            todaySignIns: []
        }
    },
    
    mounted() {
        // 从本地存储加载今日签到记录
        this.loadTodaySignIns();
        
        // 创建canvas元素用于拍照
        this.canvas = document.createElement('canvas');
    },
    
    methods: {
        // 摄像头相关方法
        async startCamera() {
            try {
                this.videoStream = await navigator.mediaDevices.getUserMedia({ 
                    video: { 
                        facingMode: 'user',
                        width: { ideal: 640 },
                        height: { ideal: 480 }
                    } 
                });
                this.showCamera = true;
                
                // 等待DOM更新
                await this.$nextTick();
                
                if (this.$refs.video) {
                    this.$refs.video.srcObject = this.videoStream;
                }
            } catch (error) {
                console.error('无法访问摄像头:', error);
                this.errors.photo = '无法访问摄像头，请检查权限设置';
            }
        },

        capturePhoto() {
            if (!this.$refs.video || !this.videoStream) {
                return;
            }

            const video = this.$refs.video;
            this.canvas.width = video.videoWidth;
            this.canvas.height = video.videoHeight;
            
            const context = this.canvas.getContext('2d');
            context.drawImage(video, 0, 0);
            
            // 转换为base64格式
            this.capturedImage = this.canvas.toDataURL('image/jpeg', 0.8);
            
            // 停止摄像头
            this.stopCamera();
        },

        stopCamera() {
            if (this.videoStream) {
                this.videoStream.getTracks().forEach(track => track.stop());
                this.videoStream = null;
            }
            this.showCamera = false;
        },

        retakePhoto() {
            this.capturedImage = null;
            this.clearMessages();
            this.startCamera();
        },

        clearPhoto() {
            this.capturedImage = null;
            this.clearMessages();
            if (this.errors.photo) {
                delete this.errors.photo;
            }
        },

        // 签到功能
        async signIn() {
            if (!this.capturedImage) {
                this.errors.photo = '请先拍摄照片进行人脸识别';
                return;
            }

            this.isSubmitting = true;
            this.uploadProgress = 0;
            this.clearMessages();

            try {
                // 将base64图片转换为Blob
                const imageBlob = await this.dataURLtoBlob(this.capturedImage);
                
                // 创建FormData
                const formdata = new FormData();
                formdata.append("file", imageBlob, `signin_${Date.now()}.jpg`);                // API URL - 使用配置文件中的地址
                const apiUrl = getApiUrl('studentSignIn');                // 配置请求选项
                const requestOptions = {
                    method: 'POST',
                    body: formdata,
                    redirect: 'follow',
                    mode: 'cors', // 明确指定CORS模式
                    headers: {
                        // 不要设置Content-Type，让浏览器自动设置multipart/form-data
                    }
                };

                console.log('发送请求到:', apiUrl);
                console.log('请求选项:', requestOptions);

                // 模拟上传进度
                const progressInterval = setInterval(() => {
                    if (this.uploadProgress < 90) {
                        this.uploadProgress += 15;
                    }
                }, 300);

                // 发送请求
                const response = await fetch(apiUrl, requestOptions);
                
                clearInterval(progressInterval);
                this.uploadProgress = 100;                const result = await response.text();
                console.log('签到API响应:', result);
                
                // 解析响应结果
                let responseData;
                try {
                    responseData = JSON.parse(result);
                } catch (e) {
                    responseData = { message: result };
                }

                // 检查API响应中的code字段来判断是否成功
                if (responseData.code === 200 || (response.ok && !responseData.code)) {
                    // 创建签到记录
                    const signinRecord = {
                        name: responseData.studentName || responseData.name || '未识别学生',
                        time: this.formatDateTime(new Date()),
                        status: 'success',
                        statusText: responseData.message || '签到成功',
                        response: responseData
                    };

                    // 添加到今日签到记录
                    this.todaySignIns.unshift(signinRecord);
                    this.saveTodaySignIns();

                    // 显示成功消息
                    this.successMessage = `签到成功！${signinRecord.name} - ${signinRecord.time}`;

                    // 清除照片，准备下一次签到
                    setTimeout(() => {
                        this.capturedImage = null;
                        this.successMessage = '';
                    }, 3000);

                } else {
                    // API返回了错误码或HTTP状态不是ok
                    const errorMessage = responseData.message || `签到失败: ${response.status} ${response.statusText}`;
                    throw new Error(errorMessage);
                }            } catch (error) {
                console.error('签到失败:', error);
                
                // 检查是否是CORS错误
                let errorMessage = error.message;
                if (error.name === 'TypeError' && error.message.includes('Failed to fetch')) {
                    errorMessage = 'CORS错误：无法连接到后端服务器。这可能是因为:\n' +
                                 '1. 后端服务器未配置CORS允许跨域请求\n' +
                                 '2. 后端服务器未启动 (http://localhost:8080)\n' +
                                 '3. 网络连接问题\n\n' +
                                 '解决方案：\n' +
                                 '- 联系后端开发人员配置CORS\n' +
                                 '- 或使用start-dev.bat启动开发环境';
                }
                
                // 记录失败的签到尝试
                const failedRecord = {
                    name: '未识别',
                    time: this.formatDateTime(new Date()),
                    status: 'error',
                    statusText: '签到失败',
                    error: errorMessage
                };
                
                this.todaySignIns.unshift(failedRecord);
                this.saveTodaySignIns();
                
                this.errorMessage = errorMessage;
                
                // 5秒后清除错误消息
                setTimeout(() => {
                    this.errorMessage = '';
                }, 10000); // 延长显示时间以便阅读
                
            } finally {
                this.isSubmitting = false;
                this.uploadProgress = 0;
            }
        },

        // 工具方法
        async dataURLtoBlob(dataURL) {
            const response = await fetch(dataURL);
            return response.blob();
        },

        formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },

        getTodayKey() {
            const today = new Date();
            return `signin_${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
        },

        loadTodaySignIns() {
            const todayKey = this.getTodayKey();
            const savedSignIns = localStorage.getItem(todayKey);
            if (savedSignIns) {
                this.todaySignIns = JSON.parse(savedSignIns);
            }
        },

        saveTodaySignIns() {
            const todayKey = this.getTodayKey();
            localStorage.setItem(todayKey, JSON.stringify(this.todaySignIns));
        },

        clearMessages() {
            this.successMessage = '';
            this.errorMessage = '';
            this.errors = {};
        },

        clearTodayRecords() {
            if (confirm('确定要清空今日签到记录吗？')) {
                this.todaySignIns = [];
                const todayKey = this.getTodayKey();
                localStorage.removeItem(todayKey);
                this.successMessage = '今日签到记录已清空';
                setTimeout(() => {
                    this.successMessage = '';
                }, 2000);
            }
        }
    },

    watch: {
        'capturedImage'() {
            if (this.errors.photo) {
                delete this.errors.photo;
            }
        }
    },

    beforeUnmount() {
        // 组件销毁前停止摄像头
        this.stopCamera();
    }
}).mount('#signin-app');
